package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.db.UserManager
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.SecKillTakeOrderFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.SecKillSubBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods.DeliveryInfoFragment
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.wallet.db.UserInfoManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import org.greenrobot.eventbus.EventBus

class SecKillTakeOrderFragment : BaseDataBindingFragment<SecKillTakeOrderFragmentBinding>(),
    View.OnClickListener {

    companion object {
        fun newInstance(mBean: SecKillSubBean): SecKillTakeOrderFragment {
            val args = Bundle()
            args.putSerializable("mBean", mBean)
            val fragment = SecKillTakeOrderFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var mBean: SecKillSubBean? = null

    private val deliveryInfo = DeliveryInfoFragment.newInstance()

    private val minCount = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBean = arguments?.getSerializable("mBean") as SecKillSubBean
        mBean?.selectCount = minCount
    }

    override fun layoutId(): Int {
        return R.layout.sec_kill_take_order_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setTitle(R.string.confirm_take_order)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        loadRootFragment(R.id.mDeliveryLayout, deliveryInfo)

        viewBinder.mEntity = mBean

        viewBinder.onViewClick = this

        GlideApp.with(view)
            .load(mBean?.goodsLogo)
            .centerCrop()
            .into(viewBinder.icon)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.goodsType -> {
//                val secKillGoodTypePop = SecKillGoodTypePop(_mActivity)
//                secKillGoodTypePop.mBean = mBean
//                XPopup.Builder(_mActivity)
//                    .hasShadowBg(false)
//                    .setPopupCallback(object : SimpleCallback() {
//                        override fun onDismiss(popupView: BasePopupView?) {
//                            super.onDismiss(popupView)
//                        }
//                    })
//                    .asCustom(secKillGoodTypePop)
//                    .show()
            }
            R.id.discount -> {
                val selectCount = mBean?.selectCount ?: minCount

                if (selectCount <= minCount) return

                mBean?.selectCount = selectCount - 1

                viewBinder.mEntity = mBean
            }
            R.id.plus -> {
                val selectCount = mBean?.selectCount ?: minCount

                val skpNums = mBean?.skpNums ?: minCount

                if (selectCount >= skpNums) return

                mBean?.selectCount = selectCount + 1

                viewBinder.mEntity = mBean
            }
            R.id.toBuy -> {
                val mPop = PayingPassWordVerifyPop(_mActivity)
                XPopup.Builder(_mActivity)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
                            if (mPop.getIsOnVerifyPop()) {
                                if (mPop.getVerifyPop()) {
                                    buyGoods()

                                } else {
                                    Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    })
                    .asCustom(mPop)
                    .show()
            }
        }
    }

    private fun buyGoods() {
        val orderDesc = viewBinder.orderDesc.text?.toString()
        val addressSpot = deliveryInfo.getAddressSpot()
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        RestClient.builder()
            .url(R.string.saveSpikeOrder)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "goodsColor" to "${mBean?.goodsColor}",
                        "goodsSize" to "${mBean?.goodsSize}",
                        "orderDesc" to "$orderDesc",
                        "payType" to "${mBean?.payType}",
                        "receiverAddr" to "${addressSpot?.recAddr}",
                        "receiverPhone" to "${addressSpot?.recPhone}",
                        "receiverName" to "${addressSpot?.recName}",
                        "skpid" to "${mBean?.sid}",
                        "uId" to userInfo?.uid
                    )
                )
            )
            .success {
                Toast.makeText(_mActivity, "下单成功", Toast.LENGTH_SHORT).show()
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                getUserBalanceInfo(_mActivity)
                onBackPressedSupport()
            }.failure {
                Toast.makeText(_mActivity, "下单失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }


}